package com.gitee.magic.context.converter;

import java.lang.reflect.Array;

import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.json.JsonArray;

/**
 * @author start
 */
public class ArraysConverterEditor extends AbstractConverterEditor<String> {

	public ArraysConverterEditor(Class<?> prototype) {
		super(prototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			JsonArray ja = new JsonArray(String.valueOf(value));
			Class<?> clazz=getPrototype().getComponentType();
			AbstractConverterEditor<?> editor=ConverterEditorUtils.getBasicConverter(clazz);
			Object o = Array.newInstance(clazz, ja.length());
			for (int i = 0; i < ja.length(); i++) {
				editor.restore(ja.get(i));
				Array.set(o, i, editor.getValue());
			}
			setValue(o);
		}
	}

	@Override
	public String converter() {
		if (getSource() == null) {
			return null;
		}
		return getSource().toString();
	}
	
	@Override
	public void setValue(Object value) {
		super.setValue(value);
		if(getValue()!=null) {
			JsonArray jsons = new JsonArray();
			int length=Array.getLength(getValue());
			for(int i=0;i<length;i++) {
				Object data=Array.get(getValue(), i);
				AbstractConverterEditor<?> editor=ConverterEditorUtils.getBasicConverter(data.getClass());
				editor.setValue(data);
				jsons.put(editor.getSource());
			}
			setSource(jsons);
		}
	}

}
